import os
import re

from docx import Document
from write.ShipReviewFrom import ShipReviewFrom
from write.CargoReviewFrom import CargoReviewFrom
from write.ShipEvaluation import ShipEvaluation
from write.CargoEvaluation import CargoEvaluation
from write.CopyContract import CopyContract
from write.CargoBenefitCalculation import CargoBenefitCalculation
from util import Util


class Attachment:
	def __init__(self, inputPath, outputPath):
		self.inputPath = inputPath
		self.outputPath = outputPath
		self.cargoTextDic = {}
		self.cargoUnderlineDic = {}
		self.shipTextDic = {}
		self.shipUnderlineDic = {}

	def read(self):
		"""
		抽取合同内容，并且把合同复制为合同附件
		:return:
		"""
		for file in Util.listFile(self.inputPath):
			if re.match(".DS_Store", file) or re.match(".Ds_Store", file) or re.match("~", file):  # 跳过奇怪的共享文件
				continue
			filePath = os.path.join(self.inputPath, file)
			doc = Document(filePath)
			contractType = self._checkContractType(doc.paragraphs)

			for paragraph in doc.paragraphs:
				self._matchTextByUnderline("甲方：", paragraph, contractType)
				self._matchTextByUnderline("乙方：", paragraph, contractType)
				self._matchTextByUnderline("航次：", paragraph, contractType)
				self._matchTextByUnderline("装货港：", paragraph, contractType)
				self._matchTextByUnderline("卸货港：", paragraph, contractType)
				self._matchTextByUnderline("受载期", paragraph, contractType)
				self._matchTextByUnderline("货种：", paragraph, contractType)
				self._matchTextByUnderline("货量：", paragraph, contractType)
				self._matchTextByUnderline("基本运价：", paragraph, contractType)
				self._matchTextByUnderline("允许装卸时间：", paragraph, contractType)
				self._matchTextByUnderline("装卸时间起算及终止：", paragraph, contractType)
				self._matchTextByUnderline("装卸时间起算及终止：", paragraph, contractType)
				self._matchTextByUnderline("滞速费率：", paragraph, contractType)
				self._matchTextByUnderline("航次运费付款", paragraph, contractType)
				self._matchTextByUnderline("港内超一次移泊费用计算方式：", paragraph, contractType)
				self._matchTextByUnderline("特别约定条款：", paragraph, contractType)
				self._matchTextByUnderline("签约日期", paragraph, contractType)
			self._matchDemurrageByTable("滞速费率", doc.tables, contractType)
			self._copyContract(contractType, filePath)

		return "{shipName}V{voyage}".format(shipName=self.shipUnderlineDic["航次"][0],
		                                    voyage=self.shipUnderlineDic["航次"][1])

	def write(self):
		"""
		生成其余附件
		"""
		srf = ShipReviewFrom()
		srf.setDic(self.cargoTextDic, self.cargoUnderlineDic, self.shipTextDic, self.shipUnderlineDic)
		srf.write()

		cbc = CargoBenefitCalculation()
		cbc.setDic(self.cargoTextDic, self.cargoUnderlineDic, self.shipTextDic, self.shipUnderlineDic)
		cbc.write()

		crf = CargoReviewFrom()
		crf.setDic(self.cargoTextDic, self.cargoUnderlineDic, self.shipTextDic, self.shipUnderlineDic)
		crf.write()

		se = ShipEvaluation()
		se.setDic(self.cargoTextDic, self.cargoUnderlineDic, self.shipTextDic, self.shipUnderlineDic)
		se.write()

		ce = CargoEvaluation()
		ce.setDic(self.cargoTextDic, self.cargoUnderlineDic, self.shipTextDic, self.shipUnderlineDic)
		ce.write()

	def show(self):
		"""
		显示两个字典的内容
		"""
		print("-------------------textDic-----------------------")
		for key, value in self.cargoTextDic.items():
			print('CargoText: *{key}*:({value})'.format(key=key, value=value))
		print("-------------------underlineDic-----------------------")
		for key, value in self.cargoUnderlineDic.items():
			print('CargoUnderline: *{key}*:{value}'.format(key=key, value=value))
		print("-------------------textDic-----------------------")
		for key, value in self.shipTextDic.items():
			print('CargoText: *{key}*:({value})'.format(key=key, value=value))
		print("-------------------underlineDic-----------------------")
		for key, value in self.shipUnderlineDic.items():
			print('CargoUnderline: *{key}*:{value}'.format(key=key, value=value))

	def _matchTextByUnderline(self, pattern, paragraph, contractType):
		"""
		run中通过关键词抽取下划线内容的函数
		:param pattern: 匹配字符
		:param paragraph: word中的段落对象
		"""
		match = re.search(pattern, paragraph.text)
		check_1 = re.match("签约甲方", paragraph.text)
		check_2 = re.match("签约乙方", paragraph.text)
		# 检测索引是否包含在paragraph内
		if match is not None and check_1 is None and check_2 is None:
			lineFlag = False  # 判断多下划线时一个下划线结束的标志位
			tempText = ""  # 一段下划线的内容
			textList = []  # 所有下划线的list
			for run in paragraph.runs:
				if run.underline == True and run.text.strip() != "":
					tempText += run.text.strip()
				if run.underline is None and tempText != "":
					lineFlag = True

				# 横线结束就是抽取信息，并把标志位初始化
				if lineFlag == True:
					# 标记要删除的标点符号
					punctuation = """！？｡＂＃＄％＆＇（）＊＋－：；＜＝＞＠［＼］＾＿｀｛｜｝～｟｠｢｣､、〃》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘'‛“”„‟…‧﹏"""
					re_punctuation = "[{}]+".format(punctuation)
					textList.append(re.sub(re_punctuation, "", tempText))  # 正则匹配选取中文英文数字字符
					tempText = ""
					lineFlag = False
			# 船合同来的信息放入船字典，货合同放货字典
			if contractType == "ship":
				self.shipUnderlineDic[pattern.strip("：")] = textList
				self.shipTextDic[pattern.strip("：")] = paragraph.text[match.regs[0][1]:].strip("。").strip("：").strip()
			else:
				self.cargoUnderlineDic[pattern.strip("：")] = textList
				self.cargoTextDic[pattern.strip("：")] = paragraph.text[match.regs[0][1]:].strip("。").strip("：").strip()

	def _matchDemurrageByTable(self, pattern, tables, contractType):
		if contractType == "ship":
			if pattern not in self.shipUnderlineDic.keys() or len(self.shipUnderlineDic[pattern]) == 0:
				for table in tables:
					breakFlag, isDemurrageTable = False, False
					tb_rows = table.rows

					for i in range(len(tb_rows)):
						row_cells = tb_rows[i].cells
						"""读取每一行单元格内容"""
						for cell in row_cells:
							if re.search("滞期", cell.text):
								isDemurrageTable = True
								breakFlag = True
								break
						if breakFlag is True:
							break

					tableData = []
					if isDemurrageTable is True:
						for i in range(len(tb_rows)):
							rowData = []
							row_cells = tb_rows[i].cells
							"""读取每一行单元格内容"""
							for cell in row_cells:
								rowData.append(cell.text)  # 单元格内容
							tableData.append(rowData)
						self.shipUnderlineDic["指数滞速费"] = tableData

	# else:
	# 	if pattern not in self.cargoUnderlineDic.keys() or len(self.cargoUnderlineDic[pattern]) == 0:
	# 		tb_rows = tables[-1].rows
	# 		tableData = []
	# 		for i in range(len(tb_rows)):
	# 			rowData = []
	# 			rowCells = tb_rows[i].cells
	# 			# 读取每一行单元格内容
	# 			for cell in rowCells:
	# 				# 单元格内容
	# 				rowData.append(cell.text)
	# 			tableData.append(rowData)
	# 		self.cargoUnderlineDic["指数滞速费"] = tableData

	def _checkContractType(self, paragraphs):
		for paragraph in paragraphs:
			if re.search("甲方", paragraph.text) and re.search("广州振华航科有限公司", paragraph.text):
				return "ship"
		return "cargo"

	def _copyContract(self, contractType, filePath):
		cc = CopyContract()
		cc.setDic(self.cargoTextDic, self.cargoUnderlineDic, self.shipTextDic, self.shipUnderlineDic)
		cc.setType(contractType)
		cc.setOldPath(filePath)
		cc.write()
